package net.lab1024.sa.base.module.support.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import net.lab1024.sa.base.common.domain.EventBase;
import net.lab1024.sa.base.common.domain.EventBaseAlert;
import net.lab1024.sa.base.kafka.KafkaProducerService;
import net.lab1024.sa.base.module.support.elasticsearch.domain.form.EventBaseEsQueryForm;
import net.lab1024.sa.base.module.support.elasticsearch.domain.kql.KqlParser;
import net.lab1024.sa.base.module.support.elasticsearch.service.EventBaseEsService;
import net.lab1024.sa.base.utils.MvelUtils;
import net.lab1024.sa.base.utils.TextConversionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class ApiRestController {

    @Autowired
    private RestHighLevelClient esClient;
    @Autowired
    private KafkaProducerService kafkaProducerService;
    @Autowired
    private EventBaseEsService eventBaseEsService;
    @Data
    public static class QueryResponse {
        private Boolean ok = true;
        private String msg;
        private Map<String, Object> data = new HashMap<>();
        private List<Map<String, Object>> list = new ArrayList<>();
        private Long total = 0L;
    }

    @NoNeedLogin
    @PostMapping("/api/open/list")
    public List<Map<String, Object>> openList(@RequestBody EventBaseEsQueryForm request) {
        try {
            request.setPageSize(10000);
            // 如果有 aisql，将其转换为 ES 查询条件
            if (StringUtils.isNotBlank(request.getAisql())) {
                // 使用 KqlParser 解析 KQL 查询为 ES 查询
                JSONObject esQuery = KqlParser.parseKqlToEsQuery(request.getAisql());
                if (esQuery != null) {
                    // 将JSONObject转换为Map
                    Map<String, Object> queryMap = JSON.parseObject(esQuery.toJSONString(), Map.class);
                    request.setEsQuery(queryMap);
                }
            }
            // 获取查询结果
            List<EventBase> eventBases = eventBaseEsService.queryList(request);
            List<Map<String, Object>> list = new ArrayList<>();
            
            // 转换查询结果格式
            for (EventBase eventBase : eventBases) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("deviceName", eventBase.getDeviceName());
                resultMap.put("alarmName", eventBase.getEventName());
                resultMap.put("eventId", eventBase.getEventId());
                resultMap.put("message", eventBase.getDetail());
                resultMap.put("alarm_source", eventBase.getDeviceName() + "_" + eventBase.getDeviceIp());
                resultMap.put("ioc", eventBase.getAttackResult());
                resultMap.put("dvc_action", eventBase.getBlocked());
                resultMap.put("alarm_result", eventBase.getAttackResult());
                resultMap.put("dest_host_name", eventBase.getReqHost());
                resultMap.put("request_url_query", eventBase.getReqUrl());
                resultMap.put("response_code", eventBase.getRspCode());
                list.add(resultMap);
            }

            return list;
        } catch (Exception e) {
            log.error("查询安全事件列表失败", e);
            throw e;
        }
    }

    @NoNeedLogin
    @PostMapping("/mvel2/check")
    public Map mock(String json, String str) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            String o = jsonObject.getString("_source");
            EventBaseAlert eventBaseAlert = JSONObject.parseObject(o, EventBaseAlert.class);
            String cnversion = TextConversionUtils.cnversion(str);
            String s = MvelUtils.checkAlert(eventBaseAlert, cnversion);
            objectObjectHashMap.put("msg", s);
            kafkaProducerService.sendMessage("test-alert",JSONObject.toJSONString(eventBaseAlert));
            return objectObjectHashMap;
        } catch (Exception e) {
            return (Map) objectObjectHashMap.put("err",e.getMessage());

        }


    }
    /**
     * 模拟kafka数据 数据只会记录到告警中
     * @param json
     * @return
     */
    @NoNeedLogin
    @PostMapping("/mock/json")
    public Map mockKakfaJson(String json) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            String o = jsonObject.getString("_source");
            EventBaseAlert eventBaseAlert = JSONObject.parseObject(o, EventBaseAlert.class);
            kafkaProducerService.sendMessage("flink-rule",JSONObject.toJSONString(eventBaseAlert));
            objectObjectHashMap.put("msg", "发送成功");
            return objectObjectHashMap;
        } catch (Exception e) {
            return (Map) objectObjectHashMap.put("err",e.getMessage());

        }


    }




}
